package com.mew.common.util;

import java.io.*;

public class TxtUtils {

    //根路径
    public static String rootpath = System.getProperty("user.dir");

    public static String byFile(String path){

        String url = rootpath +File.separator+ path;
        //没配置 true
        if (!new File(url).exists()){
            return "";
        }
        InputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(url));
            int n = 0;
            StringBuilder builder = new StringBuilder();
            while ((n = in.read())!=-1){
                builder.append((char)n);
            }
            String txt = builder.toString();

            return txt;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } finally {
            try {
                if (null!=in){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void stringOut(String file,String txt) {
        OutputStreamWriter fw = null;
        try {
            //如果文件存在，则追加内容；如果文件不存在，则创建文件
            File f=new File(file);
            fw = new OutputStreamWriter(new FileOutputStream(rootpath + File.separator + file, false), "utf-8");
            //fw = new FileWriter(f, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PrintWriter pw = new PrintWriter(fw);
        pw.println(txt);
        pw.flush();
        try {
            fw.flush();
            pw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
